package com.example.sprotsapi.Config;

import com.example.sprotsapi.Utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器：验证用户是否登录
 * 重写 preHandle 方法
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 request 的 header 中获得 token 值
        String token = request.getHeader("Authorization");
        Map<String,Object> map = new HashMap<>();
        // 验证 token, JwtUtil 是自己定义的类，里面有个方法验证 token
        String sub = JwtUtil.validateToken(token);
        if (sub == null || sub.equals("")) {
            map.put("msg","登录失效");
            map.put("code","-1");
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        }
        // 更新 token 有效时间
        if (JwtUtil.isNeedUpdate(token)) {
            // 过期就创建新的 token 给前端
            String newToken = JwtUtil.createToken(sub);
            response.setHeader(JwtUtil.USER_LOGIN_TOKEN, newToken);
        }
        return true;
    }
}
